package logic

import (
	"context"

	"mail/service/account/rpc/account"
	"mail/service/receipt/model"
	"mail/service/receipt/rpc/internal/svc"
	"mail/service/receipt/rpc/receipt"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/status"
)

type ConvergeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewConvergeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ConvergeLogic {
	return &ConvergeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ConvergeLogic) Converge(in *receipt.ConvergeRequest) (*receipt.ConvergeResponse, error) {
	// todo: add your logic here and delete this line
	_, err := l.svcCtx.AccountRpc.Particular(l.ctx, &account.ParticularRequest{
		Id: in.Uid,
	})
	if err != nil {
		return nil, err
	}

	reply, err := l.svcCtx.ReceiptModel.Converge(in.Uid, 0, 10)
	if err != nil {
		if err == model.ErrNotFound {
			return nil, status.Error(100, "receipt isn't exists.")
		}
		return nil, status.Error(500, err.Error())
	}
	designation := make([]*receipt.SceneryResponse, 0, 10)
	for _, each := range reply {
		designation = append(designation, &receipt.SceneryResponse{
			Id:     each.Id,
			Uid:    each.Uid,
			Pid:    each.Pid,
			Amount: each.Amount,
			Status: each.Status,
		})
	}
	return &receipt.ConvergeResponse{
		Data: designation,
	}, nil
}
